package com.lagou.controller;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.GetObjectRequest;
import com.aliyun.oss.model.OSSObject;
import com.lagou.bean.DeleteResult;
import com.lagou.bean.DownLoadResult;
import com.lagou.bean.UpLoadResult;
import com.lagou.config.AliyunConfig;
import com.lagou.service.FileUpLoadService;
import jdk.nashorn.internal.ir.LiteralNode;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.UUID;

@Controller
@RequestMapping("/oss")
public class UploadController {
    @Autowired
    private FileUpLoadService fileUpLoadService;
    @Autowired
    private OSSClient ossClient;

    @Autowired
    private AliyunConfig aliyunConfig;

    @PostMapping("/upload")
    @ResponseBody
    public UpLoadResult upload(@RequestParam("file") MultipartFile multipartFile) {
        return fileUpLoadService.upload(multipartFile);
    }

    @GetMapping("/download")
    @ResponseBody
    public void download(String fileName,HttpServletResponse response) throws IOException {//根据图片名进行文件的下载
//        return fileUpLoadService.download(fileName);
        String filePath = getFilePath(fileName);
        // 下载OSS文件到本地文件。如果指定的本地文件存在会覆盖，不存在则新建。
        OSSObject object = ossClient.getObject(new GetObjectRequest(aliyunConfig.getBucketName(), fileName));
        InputStream inputStream = object.getObjectContent();
        try {
            DownLoadResult downLoadResult = new DownLoadResult();
            if (object == null) {
                response.setStatus(400);
            }

            BufferedImage img = ImageIO.read(inputStream);

            if (img != null) {
                String format = fileName.substring(fileName.lastIndexOf(".") + 1);
                ImageIO.write(img, format, response.getOutputStream());
            }
        } catch (Exception e) {
            inputStream.close();
            response.setStatus(400);
        }finally {
            inputStream.close();
        }
    }

    @RequestMapping("/delete")
    @ResponseBody
    public DeleteResult delete(String fileName) {//根据图片名进行文件的删除
        return fileUpLoadService.delete(fileName);
    }

    // 生成不重复的文件路径和文件名
    private String getFilePath(String sourceFileName) {
        DateTime dateTime = new DateTime();
        return "images/" + dateTime.toString("yyyy")
                + "/" + dateTime.toString("MM") + "/"
                + dateTime.toString("dd") + "/" + UUID.randomUUID().toString() + "." +
                StringUtils.substringAfterLast(sourceFileName, ".");
    }
}
